package com.ywk.mapperRegister.core;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * FactoryBean的作用：https://blog.csdn.net/yx444535180/article/details/124605575
 *
 * @Author zbh
 * @Date 2023/5/7
 */
public class DBMapperFactoryBean implements FactoryBean {

    private Class mapperClass;

    private SqlSession sqlSession;

    public DBMapperFactoryBean(Class mapperClass) {
        this.mapperClass = mapperClass;
    }

    /*=======================模仿 mybatis 源码方式（此种方式可以把sql写在xml里）=================================*/
    private boolean externalSqlSession;

    @Autowired
    public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) {
        if (!this.externalSqlSession) {
            this.sqlSession = new SqlSessionTemplate(sqlSessionFactory);
        }
    }
    @Autowired
    public void setSqlSessionTemplate(SqlSessionTemplate sqlSessionTemplate) {
        this.sqlSession = sqlSessionTemplate;
        this.externalSqlSession = true;
    }
    /*=============================================================*/

    /**
     * 这种方式只能结合 @Select 来执行sql，不能写在xml文件
     */
   /* @Autowired
    public void setSqlSession(SqlSessionFactory sqlSessionFactory) {
        sqlSessionFactory.getConfiguration().addMapper(mapperClass);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        this.sqlSession = sqlSession;
    }*/


    /**
     * 此时XXXMapper 的代理对象是自定义的，我们需要 mybatis 生成的代理对象，
     * Mybatis 是通过sqlSession.getMapper(XXMapper.class);生成代理对象的
     * @return
     * @throws Exception
     */
    /*@Override
    public Object getObject() throws Exception {
        Object mapperProxy = Proxy.newProxyInstance(YwkMapperFactoryBean.class.getClassLoader(), new Class[]{mapperClass}, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                System.out.println(method.getName() + "--------" + mapperClass);
                return null;
            }
        });
        return mapperProxy;
    }*/

    @Override
    public Object getObject() {
        return sqlSession.getMapper(mapperClass);
    }

    @Override
    public Class<?> getObjectType() {
        return mapperClass;
    }

}
